<?php defined('SYSPATH') or die('No direct script access.');

class Helper {
	
	public static function image_resize($file = NULL, $width = 0, $height = 0, $save = NULL, $save_ratio = NULL, $bg = TRUE) {

		$quality = 90;
		
		if (!file_exists($file)) return;

		$image = Image::factory($file);
		
		if ($bg) $image->background('#fff');

		if (!$height) $height = ($width / ($image->width / ($image->height - $image->width))) * ($image->height / ($image->height - $image->width));
		if (!$width) $width = ($height / ($image->height / ($image->width - $image->height))) * ($image->width / ($image->width - $image->height));

		$h = $height;
		$w = $width;

		if ($save_ratio)
			$image->resize($height < $width ? NULL : $width, $height > $width ? NULL : $height);
		else
		{
			$h = $height;
			$w = $width * (($height * ($image->width / $image->height)) / $width);
			if ($w < $width)
			{
				$w = $width;
				$h = $height * (($width * ($image->height / $image->width)) / $height);
			}
			$image->resize($w, $h);
		}

		if (!$save_ratio)
		{
			$image->crop($w < $width ? $w : $width, $h < $height ? $h : $height, $w < $width ? ($width - $w) / 2 : NULL, $h < $height ? ($height - $h) / 2 : NULL);
		}
		
		$image->save($save, $quality);
	}

}
